import json
import threading
import time

import requests

from SqrtS.tools.load_theme import load_theme
from SqrtS.tools.font import SqrtSFont

from SqrtS.Widgets.Text import Texts
from SqrtS.Widgets.Audio import Audio
from SqrtS.tools.image import ImageSurface
from SqrtS.Widgets.Button import ImageButton
from SqrtS.AdvancedWidgets.Sidebar import SideBar

from LyricParser import LyricParser



class MusicGetter:
    def __init__(self):
        """
        音乐解析模块
        """

        self.target_url = "https://music.liuzhijin.cn/"
        self.default_origin = "netease"
        self.data = {"input": "", "filter": "name", "type": self.default_origin, "page": "1"}
        self.music_name = ""
        self.response_list = []

    def get_music(self, music_name: str):
        """
        爬取音乐信息
        :param music_name: 音乐名称
        :return:
        """

        self.headers = {
            "accept": "application/json, text/javascript, */*; q=0.01",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "content-length": "50",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "cookie": "Hm_lvt_50027a9c88cdde04a70f5272a88a10fa=1682781321; Hm_lpvt_50027a9c88cdde04a70f5272a88a10fa=1682781321",
            "origin": "https://music.liuzhijin.cn",
            "referer": f"https://music.liuzhijin.cn/?name={self.music_name}&type={self.default_origin}",
            "sec-ch-ua": '"Chromium";v="112", "Microsoft Edge";v="112", "Not:A-Brand";v="99"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "Windows",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36 Edg/112.0.1722.64",
            "x-requested-with": "XMLHttpRequest",
        }
        self.music_name = music_name.replace(" ", "+")
        self.data = {"input": self.music_name, "filter": "name", "type": self.default_origin, "page": "1"}
        response = requests.post(self.target_url, headers=self.headers, data=self.data, verify=False)
        self.response_list = json.loads(response.text)["data"]
        # for i in response_list:
        #     print(i)

    def get_url(self, num):
        """
        获取链接
        :param num: 下标
        :return: 列表，表示结果
        """

        return self.response_list[num]

    def get_num(self):
        """
        获取数目
        :return: int类型，表示数目
        """

        return len(self.response_list)


class MusicDownloader:

    def __init__(self):
        """
        音乐下载模块
        """

        self.headers = {
            'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.1071 SLBChan/21',
            'referer': 'https://music.163.com/'
        }

    def Download(self, url, path):
        """
        下载函数
        :param url: 下载地址链接
        :param path: 下载路径
        :return:
        """

        music_url = url
        response = requests.get(music_url, headers=self.headers, allow_redirects=False)
        url = response.headers.get('Location')

        music = requests.get(url, headers=self.headers).content

        with open(path, mode='wb') as file:
            file.write(music)


class MusicModule:

    def __init__(self, roxy):
        """
        音乐模块
        :param roxy:
        """
        self.is_playing = None
        self.now_num = None
        self.roxy = roxy
        self.is_sidebar = False
        self.CachePath = "C:/RoxyCache/"

    def Search(self, keyword):
        """
        搜索音乐
        :param keyword:
        :return:
        """

        try:
            mg = MusicGetter()
            mg.get_music(keyword)

            self.results = []

            for i in range(10):
                self.results.append(mg.get_url(i))

            return self.results

        except Exception as e:
            print("Music Searching Error: ", e)

    def PlayMusic(self, num):
        """
        播放音乐
        :param num:
        :return:
        """

        self.now_num = num

        try:
            Downloader = MusicDownloader()
            Downloader.Download(self.results[num]["url"], self.CachePath + "Music/Download.mp3")
        except Exception as e:
            print("Music Downloader Error: ", e)

        try:
            self.init_Player(self.CachePath + "Music/Download.mp3")
            self.Play()
        except Exception as e:
            print("Music Player Error: ", e)

        thr_get_lyric = threading.Thread(target=self.GetLyric)
        thr_get_lyric.start()

    def GetLyric(self):
        """
        获取歌词
        :return:
        """

        try:
            while True:

                lyric_parser = LyricParser(self.results[self.now_num]["lrc"])
                now_lyric = lyric_parser.get_lyric(float(self.GetPos()))

                if len(now_lyric) == 0:
                    ...
                elif len(now_lyric) == 1:
                    self.txt_lrc2.change_text(now_lyric[1], (0, 0, 0), font=self.font_now_lrc)
                elif len(now_lyric) == 2:
                    self.txt_lrc2.change_text(now_lyric[1], (0, 0, 0), font=self.font_now_lrc)
                    self.txt_lrc3.change_text(now_lyric[2], (0, 0, 0), font=self.font_prev_lrc)
                else:
                    self.txt_lrc1.change_text(now_lyric[0], (0, 0, 0), font=self.font_prev_lrc)
                    self.txt_lrc2.change_text(now_lyric[1], (0, 0, 0), font=self.font_now_lrc)
                    self.txt_lrc3.change_text(now_lyric[2], (0, 0, 0), font=self.font_prev_lrc)
                time.sleep(0.05)

        except Exception as e:
            print("Lyric Parsing Error: ", e)

    def build(self):
        """
        开启侧边栏
        :return:
        """
        self.sidebar = SideBar(self.roxy.screen_size, 700, 0.01, "Source/wid_res.png", direction="left", x_speed=8)
        self.roxy.wd.Layout.appends([self.sidebar])
        self.sidebar.register_for_event(self.roxy.wd)
        # sidebar.move_out(self.roxy.wd)

        self.btn_pause_imglist = [
            ImageSurface("Source\\play_circle_fill.svg"),
            ImageSurface("Source\\play_circle_fill.svg"),
            ImageSurface("Source\\play_circle_fill.svg")
        ]
        self.btn_play_imglist = [
            ImageSurface("Source\\pause_circle_fill.svg"),
            ImageSurface("Source\\pause_circle_fill.svg"),
            ImageSurface("Source\\pause_circle_fill.svg")
        ]

        theme1 = load_theme("Source\\theme_root\\theme\\")
        self.font_now_lrc = SqrtSFont(30, "cnfont", theme1)
        self.font_prev_lrc = SqrtSFont(20, "cnfont", theme1)

        self.btn_play = ImageButton([80, 80], self.btn_play_imglist, IDname="btn_play")
        self.txt_return = Texts("返回", (0, 0, 0), self.font_now_lrc, IDname="txt_return")

        self.btn_play.reset_imglist(self.btn_play_imglist)
        self.btn_play.register_for_event(self.roxy.wd)
        self.btn_play.bind_call_func(self.ChangePause)

        self.txt_return.register_for_event(self.roxy.wd)
        self.txt_return.bind_call_func(self.destroy_sidebar)

        self.sidebar.appends_widgets([self.btn_play, self.txt_return])
        self.sidebar.bind_widgets_poses({"btn_play": [310, self.roxy.screen_size[1] - 150], "txt_return": [620, 80]})

        self.txt_lrc1 = Texts("", (0, 0, 0), self.font_prev_lrc, IDname="txt_lrc_0")
        self.txt_lrc2 = Texts("没有歌词", (0, 0, 0), self.font_now_lrc, IDname="txt_lrc_1")
        self.txt_lrc3 = Texts("", (0, 0, 0), self.font_prev_lrc, IDname="txt_lrc_2")
        self.txt_lrc1.register_for_event(self.roxy.wd)
        self.txt_lrc2.register_for_event(self.roxy.wd)
        self.txt_lrc3.register_for_event(self.roxy.wd)

        self.sidebar.appends_widgets([self.txt_lrc1, self.txt_lrc2, self.txt_lrc3])
        self.sidebar.bind_widgets_poses({"txt_lrc_0": [30, 250],
                                    "txt_lrc_1": [30, 350],
                                    "txt_lrc_2": [30, 450]})

    def init_Player(self, path):
        self.is_playing = False
        self.au = Audio(path=path, if_track_pos=True)

    def Play(self):
        self.is_playing = True
        self.au.play()

    def Stop(self):
        self.is_playing = False
        self.au.stop_all()

    def Pause(self):
        self.is_playing = False
        self.btn_play.reset_imglist(self.btn_pause_imglist)
        self.au.pause()

    def Unpause(self):
        self.is_playing = True
        self.btn_play.reset_imglist(self.btn_play_imglist)
        self.au.unpause()

    def SetVolumn(self, val):
        self.au.set_volume(val)

    def GetIsPlaying(self):
        return self.au.get_busy()

    def SetQueue(self, next_filename):
        self.au.queue(next_filename)

    def GetPos(self):
        return self.au.get_sound_pos()

    def ChangePause(self, args):
        if self.is_playing:
            self.Pause()
        else:
            self.Unpause()

    def destroy_sidebar(self, args):
        self.Stop()
        self.sidebar.destroy_widget(self.roxy.wd)



if __name__ == "__main__":
    mg = MusicGetter()
    mg.get_music("Faded")
    results = []
    for i in range(10):
        results.append(mg.get_url(i))
    print(results)

    num = 0

    print("123", results[num]["lrc"])
    # lyric_parser = LyricParser(results[num]["lrc"])
    # print (lyric_parser.get_lyric("61"))

    # md = MusicDownloader()
    # md.Download(mg.get_url(2)["url"], "C:/1.mp3")
    #
    # mp = MusicPlayer("C:/1.mp3")
    ...
